layui.config({
    base: "static/layui/module/",
}).extend({
    excel: 'excel/excel'
}).use(['form','layer','jquery','table','upload','excel','laytpl','element'],function() {
    var form = layui.form,
        layer = layui.layer,
        $ = layui.jquery,
        upload = layui.upload,
        element = layui.element,
        excel = layui.excel,
        laytpl = layui.laytpl,
        table = layui.table;

    let upload_type;

    table.on('toolbar(table)', function(obj){
        tableToolbarEnvent(obj);
        switch(obj.event){
            case 'addD':
                var index = layer.open({
                    type: 2
                    ,title: '新增'
                    ,area: ['50%', '100%']
                    ,content: '/manage/common/addHtml/' + object.url
                    ,btn: ['保存', '取消']
                    ,offset: 'r'
                    ,yes: function (index, layero) {
                        var body = layer.getChildFrame('body', index);
                        var iframeWindow = $(layero).find("iframe")[0].contentWindow;
                        var data = iframeWindow.getFormDataAndValidate();
                        if (!data[0]) {
                            return;
                        }

                        var master = data[1];
                        if (!master.djMaterial){
                            top.layer.msg("料号必填！", {icon: 2});
                            return;
                        }
                        master.updateTime = new Date();
                        var shadeIndex = top.layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.4});
                        $.post("/initial-stock/add", {url: object.url, obj: JSON.stringify(master)}, function (d) {
                            if (d.code == '200') {
                                top.layer.alert("新增成功", {icon: 1});
                                table.reload('table');
                            } else {
                                top.layer.msg("新增失败," + d.msg, {icon: 2});
                            }
                            top.layer.close(shadeIndex);
                            layer.close(index);
                        }, "json")
                    }
                });
                break;
            case 'updD':
                var tableCheckData = table.checkStatus(obj.config.id);
                var data = tableCheckData.data;
                if (data.length == 0) {
                    layer.msg("请选择要修改的数据");
                    return;
                }
                ;
                if (data.length != 1) {
                    layer.msg("请选择单条数据");
                    return;
                }
                ;
                var index = layer.open({
                    type: 2
                    ,title: '修改'
                    ,area: ['50%', '100%']
                    ,content: '/manage/common/editHtml/' + object.url + '/' + data[0].id
                    ,btn: ['保存', '取消']
                    ,offset: 'r'
                    ,yes: function (index, layero) {
                        var body = layer.getChildFrame('body', index);
                        var iframeWindow = $(layero).find("iframe")[0].contentWindow;
                        var d = iframeWindow.getFormDataAndValidate();
                        if (!d[0]) {
                            return;
                        }
                        var master = d[1];
                        master.id = data[0].id;

                        var shadeIndex = top.layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.4});
                        $.post("/initial-stock/update", {url: object.url, obj: JSON.stringify(master)}, function (d) {
                            if (d.code == '200') {
                                top.layer.msg("修改成功", {icon: 1});
                                table.reload('table');
                            } else {
                                top.layer.msg("修改失败," + d.msg, {icon: 2});
                            }
                            top.layer.close(shadeIndex);
                            layer.close(index);
                        }, "json")
                    }
                });
                break;
            case 'import':
                layer.confirm('请选择本次是覆盖导入还是增量导入？PS:覆盖导入将会删除原数据,增量导入只会导入原数据没有的', {
                        btn: ['覆盖导入','增量导入','取消'] //按钮
                    }
                    ,function () {
                        upload_type = "cover";
                        $("#uploadExcel")[0].click();
                    }
                    ,function () {
                        upload_type = "insert";
                        $("#uploadExcel")[0].click();
                    })
                break;
            case 'templetD':
                layer.confirm('确定要下载导入模版到本地吗？', function (index) {
                    window.location.href = "/initial-stock/download_templet";
                    layer.close(index);
                });
                break;
            case 'exportD':
                layer.confirm('确定要导出到本地吗？', function (index) {
                    window.location.href = "/initial-stock/download_export";
                    layer.close(index);
                });
                break;
        };
    });

    upload.render({
        elem: '#uploadExcel'
        ,accept: 'file' //普通文件
        ,exts: 'xlsx|xls'
        ,auto: false
        ,choose: function(obj){
            var files = obj.pushFile()
            var fileArr = Object.values(files)// 注意这里的数据需要是数组，所以需要转换一下
            var fields = {
                'djMaterial' : 'A',
                'invSum' : 'B',
            }
            // 用完就清理掉，避免多次选中相同文件时出现问题
            for (var index in files) {
                if (files.hasOwnProperty(index)) {
                    delete files[index]
                }
            }
            $('#uploadExcel').next().val('');
            uploadExcel('/initial-stock/upload/'+upload_type,fields,fileArr,excel,layer,laytpl,element)
        }
    });

    function uploadExcel(url,fields,files,excel,layer,laytpl,element) {
        try {
            excel.importExcel(files, {
                // 读取数据的同时梳理数据
                fields : fields
            }, function(data) {
                // 如果不需要展示直接上传，可以再次 $.ajax() 将JSON数据通过 JSON.stringify() 处理后传递到后端即可
                var sheetTab = undefined;

                layer.open({
                    title : '文件转换结果',
                    type: 1,
                    btn: ["确定","取消"],
                    area: [ '80%', '60%' ],
                    tipsMore : true,
                    content : laytpl($('#LAY-excel-export-ans').html()).render({
                        data : data,
                        files : files
                    }),
                    success : function(layero, index) {
                        element.on('tab(sheet)', function(data){
                            sheetTab = this.getAttribute('lay-id');
                        });
                    }
                    ,yes: function(index, layero){
                        if(sheetTab == undefined){
                            layer.msg("请先选择要导入的sheet页！",{icon:2});
                            return;
                        }
                        var result = data[0][sheetTab];
                        if(result.length < 3){
                            layer.msg("导入的sheet页没有数据！",{icon:2});
                            return;
                        }
                        var pushData = [];
                        $.each(result,function(index,e){
                            if(index > 1){
                                pushData.push(e);
                            }
                        });
                        var count = 0;
                        for(var i in pushData[0]) {
                            if(pushData[0].hasOwnProperty(i)) {
                                count++;
                            }
                        }
                        var dateField = [];
                        for(var i in fields) {
                            if(fields.hasOwnProperty(i)) {
                                count--;
                            }
                            if(fields[i].indexOf('time') || fields[i].indexOf('Time') || fields[i].indexOf('date') || fields[i].indexOf('Date')){
                                dateField.push(fields[i]);
                            }
                        }
                        if(count != 0){
                            alert('导入模板错误,导出的excel即为导入的模板！');
                            return;
                        }
                        $.post(url,{data:JSON.stringify(pushData)},function(d){
                            if(d.code == '200'){ //上传成功
                                if (d.data){
                                    layer.alert("导入成功,存在共用物料,请联系管理员核对！");
                                }else{
                                    layer.alert("导入成功！");
                                }
                                table.reload('table');
                            }else{
                                layer.alert("导入失败,"+d.msg);
                            }
                        });
                        layer.close(index); //如果设定了yes回调，需进行手工关闭
                    }
                })
            })
        } catch (e) {
            layer.alert(e.message)
        }
    }
})